#pragma once

#include <iostream>
#include <unistd.h>
#include <cstring>
#include <string>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h> // 新增：用于错误信息

// 前向声明 log_message 函数，它将在 HttpServer.cc 中定义
void log_message(const std::string& msg);

enum
{
    SocketError = 2,
    BindError,
    ListenError,
};

const int backlog = 10;

class Sock
{
public:
    Sock()
    {
    }

    ~Sock()
    {
    }

    void Socket()
    {
        sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd_ < 0)
        {
            log_message("FATAL: Failed to create socket: " + std::string(strerror(errno)));
            exit(SocketError);
        }

        // 复用 端口
        int opt = 1;
        if (setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0)
        {
            log_message("WARNING: setsockopt SO_REUSEADDR failed: " + std::string(strerror(errno)));
            // 这是一个警告，通常不是致命错误，所以不退出
        }
        
    }

    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        socklen_t len = sizeof(local);
        int n = bind(sockfd_, (struct sockaddr *)&local, len);
        if(n < 0)
        {
            log_message("FATAL: Failed to bind socket to port " + std::to_string(port) + ": " + std::string(strerror(errno)));
            exit(BindError);
        }
        log_message("INFO: Socket bound to port " + std::to_string(port));
    }

    void Listen()
    {
        int n = listen(sockfd_, backlog);
        if(n < 0)
        {
            log_message("FATAL: Failed to listen on socket: " + std::string(strerror(errno)));
            exit(ListenError);
        }
        log_message("INFO: Socket listening with backlog " + std::to_string(backlog));
    }

    int Accept(std::string *clientip, uint16_t *clientport)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int newfd = accept(sockfd_, (struct sockaddr *)&peer, &len);
        if(newfd < 0)
        {
            // 对于非阻塞accept，EAGAIN/EWOULDBLOCK是正常情况，可以不记录为错误
            // 对于阻塞accept，大多数错误都值得记录
            if (errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN) {
                log_message("WARNING: Failed to accept new connection: " + std::string(strerror(errno)));
            }
            return -1;
        }
        
        char ipstr[INET_ADDRSTRLEN]; // 使用INET_ADDRSTRLEN以确保足够大
        inet_ntop(AF_INET, &(peer.sin_addr), ipstr, sizeof(ipstr));
        *clientip = ipstr;

        *clientport = ntohs(peer.sin_port);
        log_message("INFO: Accepted connection from " + *clientip + ":" + std::to_string(*clientport) + " (newfd: " + std::to_string(newfd) + ")");
        
        return newfd;
    }

    bool Connect(const std::string &ip, const uint16_t &port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &(peer.sin_addr));

        int n = connect(sockfd_, (struct sockaddr *)&peer, sizeof(peer));
        if(n == -1)
        {
            log_message("ERROR: Failed to connect to " + ip + ":" + std::to_string(port) + ": " + std::string(strerror(errno)));
            return false;
        }
        log_message("INFO: Connected to " + ip + ":" + std::to_string(port));
        return true;
    }

    void Close()
    {
        if (sockfd_ != -1) {
            log_message("INFO: Closing socket " + std::to_string(sockfd_));
            close(sockfd_);
            sockfd_ = -1; // Prevent double close
        }
    }

    int Fd()
    {
        return sockfd_;
    }

private:
    int sockfd_ = -1; // Initialize to -1
};
